package com.kehutong.house.service;
import com.kehutong.common.ExcelUtil;
import com.kehutong.common.urlconfig.FileUrlConfig;
import com.kehutong.house.entity.Supplier;
import org.apache.poi.ss.usermodel.*;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.mvc.webservice.WebService;
import org.coraframework.util.Objects;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebService("/basic/house/supplier/service")
public class SupplierService {
    static final Logger logger = LoggerFactory.getLogger(SupplierService.class);

    public final static String[] EXCEL_IMPORT_HEADER = {"供应商名称", "助记名称", "供应物品", "类型", "状态", "归属人员", "所在地区", "详细地址"
            , "企业规模", "备注信息", "联系人姓名", "尊称", "角色", "生日", "部门职务", "手机号码", "固定电话","传真号码","电子邮箱","微信账号","QQ号码","备注信息"};
    @Inject
    private FileUrlConfig fileUrlConfig;
    public Object checkFile(JSONObject jsonObject) throws Exception {
        InputStream is = fileUrlConfig.download(jsonObject.getString("fileId"));
        Workbook wb = WorkbookFactory.create(is);
        Sheet sheet = wb.getSheetAt(0);

        // 3行表头 开始读
        Row firstRow = sheet.getRow(sheet.getFirstRowNum() + 2);
        List<String> errMsgs = new ArrayList<>();

        for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
            firstRow.getCell(i).setCellType(CellType.STRING);
            String s = firstRow.getCell(i).getStringCellValue();
            if (i < EXCEL_IMPORT_HEADER.length) {
                if (!EXCEL_IMPORT_HEADER[i].equals(s)) {
                    errMsgs.add("请确认【" + EXCEL_IMPORT_HEADER[i] + "】为第" + (i + 1) + "列");
                }
            }
        }

        JSONObject errorJson = new JSONObject();
        // 表头校验结果
        if (!errMsgs.isEmpty()) {
            errorJson.put("normalCount", 0);
            errorJson.put("errCount", 0);
            errorJson.put("successCount", 0);
            errorJson.put("errMsgs", errMsgs);
            return Result.error(0, "数据解析异常", errorJson);
        }

        Map<Integer,Integer> errCount = new HashMap<>();
        Integer size = 0;

        // 第4行开始遍历获取数据
        for (int rIndex = sheet.getFirstRowNum() + 3; rIndex <= sheet.getLastRowNum(); rIndex++) {
            Row row = sheet.getRow(rIndex);
            // 校验数据
            checkExcelData(row, (rIndex + 1), errMsgs, errCount);
            size++;
        }
        errorJson.put("normalCount", size);
        if(size > 3000){
            errMsgs = new ArrayList<>();
            errMsgs.add("最多支持导入3000条数据");
            errorJson.put("errCount", 0);
            errorJson.put("successCount", 0);
            errorJson.put("errMsgs", errMsgs);
            return Result.error(0, "数据解析异常", errorJson);
        }

        // 数据读取结果
        if (!errMsgs.isEmpty()) {
            int errSum = 0;
            for (int val: errCount.keySet()) {
                errSum++;
            }
            errorJson.put("errMsgs", errMsgs);
            errorJson.put("errCount", errSum);
            errorJson.put("successCount", size - errSum);

            return Result.error(0, "数据解析异常", errorJson);
        }
        errorJson.put("errMsgs", errMsgs);
        errorJson.put("errCount", 0);
        errorJson.put("successCount", size);
        return Result.success("成功", errorJson);
    }
    private void checkExcelData(Row row, int index, List<String> errMsgs, Map<Integer,Integer> errCount) {

        String name = ExcelUtil.getCellValue(row.getCell(0));
        Supplier supplier = null;
        if (Objects.isEmpty(name)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【供应商名称】不能为空");
        }

        String goodsId = ExcelUtil.getCellValue(row.getCell(2));
        if (Objects.isEmpty(goodsId)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【供应物品id】不能为空");
        }

        String customerType = ExcelUtil.getCellValue(row.getCell(3));
        if (Objects.isEmpty(customerType)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【类型】不能为空");
        }
        String status = ExcelUtil.getCellValue(row.getCell(4));
        if (Objects.isEmpty(status)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【状态】不能为空");
        }

        String ower = ExcelUtil.getCellValue(row.getCell(5));
        if (Objects.isEmpty(ower)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【归属人员】不能为空");
        }
        String areaName = ExcelUtil.getCellValue(row.getCell(2));
        if (Objects.isEmpty(areaName)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【所在地区】不能为空");
        }else{
            String[] area_names = areaName.split(",");
            if(area_names.length < 3){
                errCount.put(index, 1);
                errMsgs.add("第" + index + "行：【所在地区】格式有误");
            }
        }

        String address = ExcelUtil.getCellValue(row.getCell(7));
        if (Objects.isNull(address)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【详细地址】不能为空");
        }

        String liaisonMan = ExcelUtil.getCellValue(row.getCell(10));
        if (Objects.isNull(liaisonMan)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【联系人姓名】不能为空");
        }
        String phone = ExcelUtil.getCellValue(row.getCell(15));
        if (Objects.isNull(phone)) {
            errCount.put(index, 1);
            errMsgs.add("第" + index + "行：【手机号码】不能为空");
        }

    }
}
